package com.getjsp.ui;

import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;

import com.baidu.mobstat.StatService;

import com.getjsp.adapter.MyViewPagerAdapter;
import com.getjsp.fragment.LikeFragment;
import com.getjsp.fragment.MainFragment;
import com.getjsp.util.HttpDownload;
import com.getjsp.util.ProgressShow;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;

import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class MainActivity extends SherlockFragmentActivity implements
		OnPageChangeListener {
	private ArrayList<Fragment> list;
	private ViewPager vp;
	private FragmentStatePagerAdapter adapter;
	private LayoutInflater inflater;
	private String[] arrStrings;
	private ActionBar actionBar;
	private long exitTime = 0;
	private Handler handler;
	private static final int SUCCESS = 1;
	private ProgressDialog pro;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		inflater = getLayoutInflater();
		// 获取ViewPager
		vp = (ViewPager) findViewById(R.id.pager);
		// 为ViewPager设置监听
		vp.setOnPageChangeListener(this);
		// 设置初始视图
		vp.setCurrentItem(0);
		list = new ArrayList<Fragment>();
		Fragment mainFragment = MainFragment.newInstance();
		Fragment linFragment = LikeFragment.newInstance();

		list.add(mainFragment);
		list.add(linFragment);
		adapter = new MyViewPagerAdapter(getSupportFragmentManager(), list);
		// 为ViewPager设置 adapter
		vp.setAdapter(adapter);
		actionBar = getSupportActionBar();
		// actionBar.setDisplayShowCustomEnabled(true);
		// actionBar.setDisplayShowTitleEnabled(true);
		/*
		 * //不在actionbar显示logo actionBar.setDisplayShowHomeEnabled(false);
		 */
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		arrStrings = getResources().getStringArray(R.array.sections);
		for (int i = 0; i < arrStrings.length; i++) {
			Tab tab = actionBar.newTab();
			tab.setCustomView(getTabView(arrStrings[i]));
			tab.setTabListener(new TabListener() {
				@Override
				public void onTabUnselected(Tab tab, FragmentTransaction ft) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onTabSelected(Tab tab, FragmentTransaction ft) {

					vp.setCurrentItem(tab.getPosition());
				}

				@Override
				public void onTabReselected(Tab tab, FragmentTransaction ft) {
					// TODO Auto-generated method stub
				}
			});
			actionBar.addTab(tab);
		}

		// 自定义TITLE背景
		/*
		 * actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.
		 * title_bj)); View title_view =
		 * LayoutInflater.from(this).inflate(R.layout.title_bj, null);
		 * actionBar.setCustomView(title_view);
		 */
		// 决定左上角图标的右侧是否有向左的小箭头。
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setLogo(R.drawable.site_icon);
		actionBar.setTitle("站长工具");
		// 百度轮盘广告
		/*new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {				
				IconsAd ad = new IconsAd(MainActivity.this);		
				ad.loadAd(MainActivity.this);
			}
		}, 2000);*/
		
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		SubMenu submenu = menu.addSubMenu("更多");
		submenu.add("推荐给好友").setOnMenuItemClickListener(
				new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("image/*");// intent.setType("text/plain");
						intent.putExtra(Intent.EXTRA_SUBJECT, "好友推荐");
						intent.putExtra(Intent.EXTRA_TEXT, "发现一款很不错的站长工具,推荐给你使用。http://getjsp.qiniudn.com/sitetools.apk");
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(Intent.createChooser(intent, getTitle()));

						return true;
					}
				});
		submenu.add("检测更新").setOnMenuItemClickListener(
				new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						pro = ProgressShow.progress(MainActivity.this, "检测更新",
								"正在检测更新,请稍候...");
						downUpdateInfo();
						handler = new Handler() {
							@Override
							public void handleMessage(Message msg) {
								switch (msg.what) {
								case SUCCESS:
									// 数据下载成功
									pro.dismiss();
									String update_json = (String) msg.obj;
									
									if (update_json == null || update_json.equals("error")) {
										Toast.makeText(MainActivity.this,
												"网络原因 检测失败", Toast.LENGTH_SHORT).show();
									} else {
										try {
											JSONObject jsonObject = new JSONObject(
													update_json)
													.getJSONObject("result");
											
											String version = jsonObject
													.getString("version");
											jsonObject
													.getString("url");
											
											if(version.equals("2")){
												Toast.makeText(MainActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();
												
											}
											if(!version.equals("2")){
												AlertDialog.Builder builder = new Builder(
														MainActivity.this);
												builder.setMessage("检测到新的版本，是否更新？");

												builder.setTitle("更新提示");

												builder.setPositiveButton("确认", new OnClickListener() {

													@Override
													public void onClick(DialogInterface dialog,
															int which) {
														dialog.dismiss();
														//用浏览器打开这个域名连接
														Uri uri = Uri.parse("http://getjsp.qiniudn.com/sitetools.apk");
														Intent intent = new Intent(Intent.ACTION_VIEW, uri);

														// 建立Intent对象，传入uri
														startActivity(intent);
														
													}
												});

												builder.setNegativeButton("取消", new OnClickListener() {

													@Override
													public void onClick(DialogInterface dialog,
															int which) {
														dialog.dismiss();
													}
												});

												builder.create().show();
											}

										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
									break;

								}
							}
						};

						return true;
					}
				});

		submenu.add("关于").setOnMenuItemClickListener(
				new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						Intent it = new Intent();
						it.setClass(MainActivity.this, AboutActivity.class);
						startActivity(it);
						return true;
					}
				});
		submenu.add("退出").setOnMenuItemClickListener(
				new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						AlertDialog.Builder builder = new Builder(
								MainActivity.this);
						builder.setMessage("亲 我们什么时候在见面 #^_^#");

						builder.setTitle("提示");

						builder.setPositiveButton("确认", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();

								MainActivity.this.finish();
							}
						});

						builder.setNegativeButton("取消", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});

						builder.create().show();

						return true;
					}
				});

		MenuItem menuItem = submenu.getItem();
		menuItem.setIcon(R.drawable.abs__ic_menu_moreoverflow_holo_light);
		menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * @Override public boolean
	 * onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
	 * getSupportMenuInflater().inflate(R.menu.main_menu, menu);
	 * 
	 * return true; }
	 */
	private View getTabView(String title) {
		View view = inflater.inflate(R.layout.tab_item_layout, null);
		TextView tv = (TextView) view.findViewById(R.id.textView);
		tv.setText(title);
		return view;

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {

		getSupportActionBar().setSelectedNavigationItem(arg0);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 百度统计
		StatService.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 百度统计
		StatService.onPause(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent it = new Intent(this, AboutActivity.class);
			startActivity(it);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * lizh henku126@163.com 2014/1/18 17:49 下载更新文件
	 */
	private void downUpdateInfo() {
		new Thread() {
			Message msg = new Message();

			public void run() {
				HttpDownload httpDownload = new HttpDownload();
				String update_info = null;
				update_info = httpDownload
						.download("http://getjsp.qiniudn.com/update.html");
				Log.i("MainActivity", update_info);
				msg.obj = update_info;
				msg.what = SUCCESS;
				handler.sendMessage(msg);

			};
		}.start();
	}
}
